package com.guodx.study.springboot.d06.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.guodx.study.springboot.d06.domain.User;
import com.guodx.study.springboot.d06.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
public class UserController {

    @Autowired
    UserService userService;

    @PostMapping("/user")
    public User add(@RequestBody User user){
        boolean save = userService.save(user);
        if(!save){
            log.error("保存用户失败");
        }
        return user;
    }

    @PutMapping("/user/{userId}")
    public User modify(@PathVariable Long userId, @RequestBody User user){
        if(userId == null){
            throw new RuntimeException("用户ID必传");
        }
        User byId = userService.getById(userId);
        if(byId == null){
            throw new RuntimeException("用户ID[ " + userId + " ]对应记录不存在");
        }

        user.setId(userId);
        boolean succ = userService.updateById(user);
        if(!succ){
            throw new RuntimeException("更新失败");
        }
        return user;
    }

    @DeleteMapping("/user/{userId}")
    public boolean delete(@PathVariable("userId") Long userId){
        return userService.removeById(userId);
    }

    @GetMapping("/user/{userId}")
    public User query(@PathVariable("userId") Long userId){
        return userService.getById(userId);
    }

    @GetMapping("/users/{pageNum}/{pageSize}")
    public List<User> queryList(@PathVariable("pageNum") Integer pageNum, @PathVariable("pageSize") Integer pageSize,
                                @RequestBody User user){
        if(pageNum <= 0) pageNum = 1;
        if(pageSize <= 0) pageSize = 2;

        PageHelper.startPage(pageNum, pageSize, false);
        QueryWrapper<User> wrapper = new QueryWrapper<>(user);
        return userService.list(wrapper);
    }
}
